const basePage = require('../../../common/BasePage')
Page({
  behaviors: [basePage],
  page: {
    size: 10,
    num: 1,
  },

  data: {
    orderTypeArr: ["", "uu跑腿", "快递", "自提", "扫码订单"],
    showCode: false,
    showUUCode: false,
    /**当前选中的订单 */
    order: {
      selfCode: "",
    },
    /**退款原因 */
    reason: '',
    showRefund: false,
    // 支付状态（1待支付、2已支付uu费用、3已全部支付、4商品已支付、5退款中、6已退款）
    payMsg: ["", "待支付", "已支付uu", "已全部支付", "已支付商品", "退款中", "已退款"],
    statusObj: {
      999: '待取货',
      1: '待取货',
      3: '待收货',
      5: '待评价',
      7: '已完成',
      8: '退款/售后',
      6: '已取消'
    },
    tabs: [{
        key: '',
        text: '全部'
      }, {
        key: 999,
        text: '预订单'
      },
      {
        key: 1,
        text: '待取货'
      },
      {
        key: 3,
        text: '待收货'
      },
      {
        key: 5,
        text: '待评价'
      },
      {
        key: 7,
        text: '已完成'
      },
      {
        key: 8,
        text: '退款/售后'
      },
      {
        key: 6,
        text: '已取消'
      },

    ],
    reasonArr: [],
    curTab: -1,
    orderList: [],
    listLoading: 0,
    pullDownRefreshing: false,

    backRefresh: false,
    status: 999,
    /**显示评价 */
    showEva: false,
    eva: {
      /**口感 */
      texture: 0,
      /**服务 */
      service: 0
    },
    /**取消请求 */
    cancelUrl: ''
  },

  onLoad(query) {
    let status = parseInt(query.status);
    status = this.data.tabs.map((t) => t.key).includes(status) ? status : '';
    this.init(status);
    this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');
  },

  onShow() {
    if (!this.data.backRefresh) return;
    this.onRefresh();
    this.setData({
      backRefresh: false
    });
  },

  service_change(e) {

    this.setData({
      "eva.service": e.detail.value
    })
  },
  loction_click(e) {
    console.log('loction_click', e);
    let order = e.currentTarget.dataset.order;
    wx.openLocation({
      latitude: order.latitude * 1,
      longitude: order.longitude * 1,
      address: order.storeAddress || '',
      name: order.storeName || '门店位置',

      success: (res) => {},
      fail: (res) => {
        wx.showToast({
          title: res.errMsg,

          icon: 'none',

        })
      },
      complete: (res) => {},
    })
  },
  texture_change(e) {

    this.setData({
      "eva.texture": e.detail.value
    })
  },
  eva_submit() {
    this.request({
      url: this.data.host + "/v1/evaluate/add/" + this.data.order.goodsOrderSn,
      method: "post",
      data: this.data.eva
    }, res => {

      wx.showToast({
        title: '评价成功',

      })
      let orderList = this.data.orderList;
      orderList.splice(this.data.order.index, 1);

      this.setData({
        showEva: false,
        orderList: orderList
      })
    })
  },
  evaluate_click(e) {
    this.setData({
      showEva: true,
      order: e.currentTarget.dataset.order
    })
    this.data.order.index = e.currentTarget.dataset.index
  },
  pick_click(e) {
    // return console.log('pick_click', e);
    let order = e.currentTarget.dataset.order;
    let index = e.currentTarget.dataset.index;
    let that = this;
    wx.navigateTo({
      url: '/pages/order/order-detail/index?sid=' + order.sid + "&orderType=" + (order.orderType || ''),
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        remove: function (data) {
          console.log("remove", data)
          let orderList = that.data.orderList;
          orderList.splice(index, 1);

          that.setData({
            orderList: orderList
          })
        },

      },
    })
  },
  uuCode_click(e) {
    let order = e.currentTarget.dataset.order;
    this.setData({
      showUUCode: true,
      order: order,
    })
  },
  /**取货码 */
  code_click(e) {
    // return console.log("code_click", e);
    let order = e.currentTarget.dataset.order;
    this.request({
      url: this.data.host + "/v1/orders/" + order.sid,
      loadingTip: "加载中..."
    }, res => {
      console.log('详情', res);
      this.setData({
        showCode: true,
        order: res.data,
      })
    })
  },
  onReachBottom() {
    console.log('onReachBottom', this.data.listLoading);
    if (this.data.listLoading === 0) {
      this.getOrderList(this.data.curTab);
    }
  },

  onPageScroll(e) {
    this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
  },

  onPullDownRefresh_(e) {
    console.log('onPullDownRefresh_', e);
    const {
      callback
    } = e.detail;
    this.setData({
      pullDownRefreshing: true
    });
    this.refreshList(this.data.curTab)
      .then(() => {
        this.setData({
          pullDownRefreshing: false
        });
        callback && callback();
      })
      .catch((err) => {
        this.setData({
          pullDownRefreshing: false
        });
        Promise.reject(err);
      });
  },

  init(status) {
    status = status !== undefined ? status : this.data.curTab;
    this.setData({
      status,
    });
    this.refreshList(status);
  },

  getOrderList(statusCode = 999, reset = false) {
    console.log('getOrderList', statusCode, reset);
    const parameter = {
      size: this.page.size,
      current: this.page.num,
      orderStatus: statusCode
    }

    this.setData({
      listLoading: 1
    });
    this.request({
      url: this.data.host + '/v1/orders/me',
      data: parameter
    }, res => {
      this.page.num++;
      console.log('订单列表', res);
      res.data.records.map(val => {
        val.goods && val.goods.map(good => {
          good.thumb = this.get_imgUrl(good.goodsImg)

          good.desc = good.goodsDesc || ""
          console.log(' good.desc', good.desc);
        })
      })
      if (reset) {
        this.setData({
          orderList: res.data.records,
          listLoading: 0
        })
      } else {
        this.setData({
          orderList: this.data.orderList.concat(res.data.records),
          listLoading: res.data.records.length > 0 ? 0 : 2,
        })

      }
    }, err => {
      this.setData({
        listLoading: 3
      })
    })

  },
  refund_change(e) {
    this.data.reason = e.detail.value;
  },
  refund_submit() {
    this.setData({
      showRefund: false
    })
    this.request({
      url: this.data.host + "/v1/orders/order-refund",
      data: {
        orderSid: this.data.order.sid,
        reason: this.data.reason
      },
      method: "post",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      loadingTip: "取消中..."
    }, res => {
      let orderList = this.data.orderList;
      orderList.splice(this.data.order.index, 1);
      this.setData({
        orderList: orderList
      })
    })
  },
  refund_click(e) {
    this.data.order.sid = e.currentTarget.dataset.sn;
    this.data.order.index = e.currentTarget.dataset.index;
    this.setData({
      showRefund: true,
    })
  },
  cancel_click(e) {
    this.data.cancelUrl = "/v1/orders/cancel"

    if (this.data.reasonArr && this.data.reasonArr.length > 0) {
      this.choose_reason(this.data.reasonArr, e.currentTarget.dataset.sn, e.currentTarget.dataset.index)
    } else {
      this.request({
        url: this.data.host + "/v1/orders/reason",
      }, res => {
        console.log('reason', res);
        this.data.reasonArr = res.data;
        this.choose_reason(this.data.reasonArr, e.currentTarget.dataset.sn, e.currentTarget.dataset.index)
      })
    }
  },
  choose_reason(reasonArr, sn, i) {
    // console.log('choose_reason', reasonArr);
    let itemList = [];
    reasonArr.map(val => {
      itemList.push(val.content)
    })
    wx.showActionSheet({
      itemList: itemList,
      alertText: '选择理由',
      // itemColor: 'itemColor',
      success: (result) => {
        console.log('选中理由', result);
        let item = reasonArr[result.tapIndex];
        this.request({
          url: this.data.host + this.data.cancelUrl,
          method: "post",
          data: {
            goodsOrderSn: sn,
            reasonSid: item.sid
          },
          // header: {
          //   'content-type': 'application/x-www-form-urlencoded',
          // }
        }, res => {
          wx.showToast({
            title: '取消成功',

          })
          let orderList = this.data.orderList;
          orderList.splice(i, 1);
          this.setData({
            orderList: orderList
          })
        })
      },

    })
  },
  onReTryLoad() {
    this.getOrderList(this.data.curTab);
  },

  onTabChange(e) {
    const {
      value
    } = e.detail;
    this.setData({
      status: value,
    });
    this.refreshList(value);
  },

  refreshList(status = 999) {
    console.log('refreshList', status);
    this.page = {
      size: this.page.size,
      num: 1,
    };
    this.setData({
      curTab: status,
      orderList: []
    });

    return Promise.all([
      this.getOrderList(status, true),
      // this.getOrdersCount(),
    ]);
  },

  onRefresh() {
    this.refreshList(this.data.curTab);
  },

});